var app = getApp();
var setting = app.globalData.setting;
console.log(setting)
var request = app.request;
// const { userInfo } = require('os');
var common = require('../../../utils/common.js');

Page({
  data: {
    showCode: false,
    statusBar: app.globalData.statusBar,
    url: setting.url,
    resourceUrl: setting.resourceUrl,
    defaultAvatar: setting.resourceUrl + "/static/images/user68.jpg",
    userInfo: {
      collect_count: 0,
      message_count: 0,
      waitPay: 0,
      waitReceive: 0,
      uncomment_count: 0,
      return_count: 0,
      user_money: 0,
      coupon_count: 0,
      pay_points: 0,
    },
    indexnum: '0',
    leaderInfo: app.globalData.leaderInfo,
    shopInfo: app.globalData.shopInfo,
    defaultMenu: false,  //默认底部菜单显示状态
    distribut: 0,
    sign: 0,
    webUrl: '',
    click: false, //避免多次发出登录请求造成token的覆盖
    is_apply: 0,
    indexnum: '0',
    cellList: [
      {
        id: 1,
        icon: "../../../images/my/wodedindan.png",
        name: "我的订单",
        marginTop: 0,
        path: "/pages/user/order_list/order_list",
      },
      {
        id: 2,
        icon: "../../../images/my/gerenziliao.png",
        name: "个人资料",
        marginTop: 20,
        path: "/pages/user/userinfo/userinfo",
      },
      {
        id: 3,
        icon: "../../../images/my/dizhiguanli.png",
        name: "地址管理",
        marginTop: 0,
        path: "/pages/user/address_list/address_list",
      },
      // {
      //   id: 4,
      //   icon: "../../../images/my/fankuijianyi.png",
      //   name: "反馈建议",
      //   marginTop: 20,
      //   path: "/pages/user/opinion/opinion",
      // },
      {
        id: 5,
        icon: "../../../images/my/xiaoxitongzhi.png",
        name: "消息通知",
        marginTop: 20,
        // path: "/pages/user/message_notice/message_notice",
        path: "/pages/user/message_release/message_release",
      },
    ],
    vipList:[]
  },

  onShow: function () {
    var that = this;
    that.data.click = false;
    this.hidetabbar();

    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo });
    }, true);

    if (app.globalData.menu_model.length == 0) {
      app.globalData.menu_index = 3
    } else {
      //遍历自定义底部，该页面在哪个位置
      for (var i in app.globalData.menu_model) {
        if (app.globalData.menu_model[i].app_url.indexOf('User/index') != -1) {
          app.globalData.menu_index = i;
        }
      }
    }
    that.setData({
      defaultMenu: app.globalData.defaultMenu,
      menu_index: app.globalData.menu_index,
      menu_model: app.globalData.menu_model,
      distribut: common.getConfigByName(app.globalData.config['config'], 'switch'),
      sign: common.getConfigByName(app.globalData.config['config'], 'sign_on_off')
    })
    var status = false;
    //先预设值，加速加载
    if (app.globalData.userInfo) {
      that.setData({ userInfo: app.globalData.userInfo });
      status = true;
    }
    if (!app.auth.isAuth()) {
      app.showLoading(null, 1500);
    }
    if (status) {
      // app.getUserInfo(function (userInfo) {
      //   console.log(userInfo,999)
      //   that.setData({ userInfo: userInfo });
      // }, true, false);
    }
    request.get('/api/user/center_menu', {
      success: function (res) {
        wx.setStorageSync('custom_menu', res.data.result.menu_list);
        that.menu(res.data.result.menu_list);
        that.setData({ head_color: res.data.result.header_background })
      }
    });

    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#D6A66E',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    wx.setBackgroundColor({
      backgroundColor: '#eeeeee',
      backgroundColorTop: '#eeeeee',
      backgroundColorBottom: '#eeeeee',
    })
    this.getCardList()
    this.getVipList()
  },
  navTo: function (e) {
    let path = e.currentTarget.dataset.item
    console.log(e.currentTarget.dataset);
    wx.navigateTo({
      url: path,
    })
  },
  getCardList: function () {
    var that = this;
    request.get(that.data.url + '/api/cart/index?type=1', {
      success: function (res) {
        that.setData({ indexnum: res.data.result.user_cart_goods_type_num })
      }
    });
  },
  getVipList: function () {
    var that = this;
    request.get(that.data.url + '/index.php?m=Api&c=MemberGoods&a=getlist', {
      success: function (res) {
        that.setData({ vipList: res.data.data.goods_list })
      }
    });
  },
  onLoad: function () {
    var that = this;
    that.setData({
      is_apply: app.globalData.is_apply
    })

    //预加载自定义缓存菜单
    if (wx.getStorageSync('custom_menu')) {
      that.menu(wx.getStorageSync('custom_menu'));
    }

    if (app.globalData.menu_model.length == 0 || !app.globalData.menu_model) {
      request.get('/api/Index/getConfig', {
        failRollback: true,
        successReload: true,
        success: function (res) {
          var data = res.data.result.config;
          var is_block = common.getConfigByName(data, 'is_block_index');

          if (is_block == 0) {
            wx.removeStorageSync('custom_data');
            app.globalData.menu_model = [];
            that.setData({ defaultMenu: true, menu_model: [] });
            app.globalData.defaultMenu = true;
          } else {
            that.getAutoData();
          }
        }
      });
    }
  },
  getAutoData: function (id) {
    var that = this;
    var url = !id ? '/api/Index/block_index' : '/api/Index/block_index/id/' + id
    request.get(url, {
      failRollback: true,
      successReload: true,
      success: function (res) {
        if (res.data.status == 1) {
          that.customRendering(res.data.result.blocks)
        }
      }
    });
  },
  bindGetUserinfo: function (res) {
    var that = this;
    if (res.detail.userInfo != undefined) {
      try {
        wx.setStorageSync('wx_user_info', res.detail);
        app.globalData.wechatUser = res.detail.userInfo;
        app.auth.checkLogin(app.globalData.code, res.detail, function (loginData) {
          app.showSuccess('授权信息成功！', function () {
            wx.removeStorageSync('first_leader');
            wx.removeStorageSync('unique_id');
            that.setData({ 'userInfo.head_pic': loginData.head_pic, 'userInfo.nickname': loginData.nickname, 'userInfo.openid': loginData.openid })
          });
        });
      } catch (e) {
        console.log(e);
      }
    } else {
      console.log('bindGetUserinfo fail . res.detail.userInfo is undefined');
    }
    return false;
  },

  /** 自定义组件渲染 */
  customRendering: function (custom) {
    var that = this;
    var data = custom;
    var menu_model = [];                    //菜单集合
    for (let z = 0; z < data.length; z++) {
      if (data[z]['block_type'] == '11') {
        menu_model = data[z];
      }
    }
    app.globalData.menu_model = menu_model.nav;
    for (var i in app.globalData.menu_model) {
      if (app.globalData.menu_model[i].app_url.indexOf('User/index') != -1) {
        app.globalData.menu_index = i;
      }
    }

    that.setData({
      defaultMenu: app.globalData.defaultMenu,
      menu_index: app.globalData.menu_index,
      menu_model: app.globalData.menu_model,
    })
  },
  /** 首次登陆小程序，授权用户信息 */
  login: function () {
    var that = this;
    if (that.data.click) return false;
    that.data.click = true;
    if (!that.data.userInfo.user_id) {
      app.getUserInfo(function (userInfo) {
        that.data.click = false;
        that.setData({ userInfo: userInfo });
      }, true, false);
    } else {
      that.data.click = false;
    }
  },
  menu: function (data) {
    var menu = [
      { id: 2, url: '/pages/user/coupon/coupon', logo: '../../../images/wy.png' },                       //我的优惠券            
      { id: 4, url: '/pages/distribut/index/index', logo: '../../../images/w1.png' },                    //我的团队
      { id: 5, url: '/pages/virtual/virtual_list/virtual_list', logo: '../../../images/w10.png' },       //虚拟订单
      { id: 6, url: '/pages/team/team_order/team_order', logo: '../../../images/w4.png' },               //拼团订单
      { id: 9, url: '/pages/user/comment/comment?status=1', logo: '../../../images/w2.png' },            //我的评价  
      { id: 12, url: '/pages/activity/coupon_list/coupon_list', logo: '../../../images/w7.png' },         //领券中心
      { id: 13, url: '/pages/user/collect_list/collect_list', logo: '../../../images/w17.png' },         //我的收藏
      { id: 14, url: '/pages/user/visit_log/visit_log', logo: '../../../images/w3.png' },                 //浏览历史             
      { id: 15, url: '/pages/user/message_notice/message_notice', logo: '../../../images/w18.png' },      //消息通知
      { id: 17, url: '/pages/user/address_list/address_list', logo: '../../../images/w8.png' },           //地址管理     
      { id: 10, url: '/pages/goods/integralMall/integralMall', logo: '../../../images/w5.png' },          //积分商城 
      // { id: 10, url: '', logo: '../../../images/w5.png' },                                              //积分兑换
      { id: 11, url: '/pages/user/sign_in/sign_in', logo: '../../../images/w11.png' },                    //我的签到
      { id: 16, url: '', logo: '../../../images/w15.png' },                                                //我的发票
      { id: 7, url: '/pages/bespeak/bespeak_list/bespeak_list', logo: '../../../images/w19.png' },          //预约订单
      { id: 8, url: '/pages/shop_order/shop_order_list/shop_order_list', logo: '../../../images/w14.png' }, //自提订单  
      { id: 3, url: '/pages/distribut/poster/poster', logo: '../../../images/w16.png' },                   //我的海报      
      { id: 18, url: '/pages/Bargain/order_list/order_list', logo: '../../../images/w16.png' },              //砍价活动和订单    
      { id: 19, url: 'webview', logo: '../../../images/w19.png' },              //使用帮助
      { id: 11, url: '/pages/user/sign_jidan/sign_jidan', logo: '../../../images/w11.png' },                    //天天领鸡蛋
    ];

    for (let i = 0; i < data.length; i++) {
      for (let ii = 0; ii < menu.length; ii++) {
        if (data[i]['menu_id'] == menu[ii]['id']) {
          data[i]['url'] = menu[ii]['url']
          data[i]['logo'] = menu[ii]['logo']
        }
      }
    }
    this.setData({ 'userInfoList.manageList': data })
    //console.log(this.data.userInfoList.manageList)
  },
  goMenu(e) {
    console.log(e);
    var that = this;
    if (e.currentTarget.dataset.url == '/pages/user/apply_leader/apply_leader') {
      var info = app.globalData.leaderInfo;
      console.log(info);
      if (info.audit_status == 0) {
        return app.showTextWarining('后台审核中')
      }
    }
    if (that.data.click) return false;
    that.data.click = true;
    that.setData({ click: false });
    wx.navigateTo({ url: e.currentTarget.dataset.url });
  },
  clickMenu(e) {
    // console.log(e,11);
    var that = this;
    if (that.data.click) return false;
    that.data.click = true;
    //在个人中心浏览其他入口页面前判断是否登录
    if (!that.data.userInfo.user_id) {
      app.getUserInfo(function (userInfo) {
        that.setData({ userInfo: userInfo, click: false });
      }, true, false);
      return false;
    }
    if (e.currentTarget.dataset.url == '/pages/distribut/index/index') {
      if (that.data.distribut == 0) {
        that.data.click = false;
        return app.showTextWarining('分销功能已关闭')
      }
    }
    if (e.currentTarget.dataset.url == '/pages/user/sign_in/sign_in') {
      if (that.data.sign == 0) {
        that.data.click = false;
        return app.showTextWarining('签到功能已关闭')
      }
    }
    if (e.currentTarget.dataset.url == 'webview') {
      this.setData({ webUrl: "/Mobile/User/userHelpList/app/3" });
      wx.navigateTo({ url: '/pages/index/webview/webview' });
      return false;
    }
    wx.navigateTo({ url: e.currentTarget.dataset.url });
  },
  /** 跳转模式 自定义页面 || 自定义菜单 || 自定义控件控件*/
  topage(e) {
    //自定义菜单
    var idx = e.currentTarget.dataset.idx;
    app.globalData.menu_index = idx;
    var page_type = this.data.menu_model[idx].url_type
    var id = this.data.menu_model[idx].app_url
    //判断跳转的类型  0 = 外部网址,1 = 小程序页面，2 = 分类商品，3 = 商品详情 ，4 = 自定义页面
    if (page_type == 1) {
      //要访问的页面idx，当前页面menu_index
      common.totabar(idx, this.data.menu_index, this.data.menu_model);
    } else if (page_type == 2) {
      wx.navigateTo({ url: '/pages/goods/goodsList/goodsList?cat_id=' + id });
    } else if (page_type == 3) {
      wx.navigateTo({ url: '/pages/goods/goodsInfo/goodsInfo?goods_id=' + id });
    } else if (page_type == 0) {
      this.setData({ webUrl: id });
      wx.navigateTo({ url: '/pages/index/webview/webview' });
    } else {
      wx.reLaunch({
        url: '../../index/customPage/customPage?id=' + this.data.menu_model[idx].app_url,
      })
    }
  },
  // toShopOrderList(type) {
  //   wx.setStorageSync('order:shop_order_list:update', true);
  //   wx.redirectTo({
  //     url: '/pages/shop_order/shop_order_list/shop_order_list?type='+type
  //   });
  // },
  /** 默认菜单 */
  topages: function (e) {
    var idx = e.currentTarget.dataset.idx;
    app.globalData.menu_index = idx;
    if (idx == 4) {
      if (!app.auth.isAuth()) {
        app.showLoading(null, 1500);
        app.getUserInfo();
        return;
      }
      if(this.data.userInfo.xcx_qrcode) {
        this.showCode();
      } else {
        app.showTextWarining('请先加入会员')
      }
    } else {
      this.setData({
        showCode: false
      })
      common.defaultTotabar(idx, 3);
    }
  },

  showCode() {
    this.setData({
      showCode: !this.data.showCode
    })
  },
  onPullDownRefresh: function (e) {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo });
      wx.stopPullDownRefresh();
    }, true);
  },
  authorization: function () {
    //再授权
    wx.openSetting({
      success: (res) => {
        //因为openSetting会返回用户当前设置
        if (res.authSetting["scope.userInfo"] === true) {
          var that = this
          app.getUserInfo(function (userInfo) {
            //更新数据
            that.setData({
              userInfo: userInfo,
            })
          })
        }
        else {
          wx.showModal({
            title: '用户未授权',
            content: '如需正常使用小程序，请点击授权按钮。',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
        }
      }
    })
  },
  hidetabbar() {  //隐藏默认tab
    wx.hideTabBar({
      fail: function () {
        setTimeout(function () { // 做了个延时重试一次，作为保底。
          wx.hideTabBar()
        }, 500)
      }
    });
  },

})